﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using DotNet.Helper;

namespace Email.WinFrom
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 从发件箱发送邮件到收件箱
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnTransaction_Click(object sender, EventArgs e)
        {
            try
            {
                MailModel model = null;
                if (!checkMail(out model))
                {
                    return;
                }

                MailResult result = MailHelper.Send(model);
                if (!result.Flag)
                {
                    throw result.Exception;
                }

                MessageBox.Show("发送成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 异步发送邮件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSendAsync_Click(object sender, EventArgs e)
        {
            MailModel model = null;
            if (!checkMail(out model))
            {
                return;
            }

            MailResult result = MailHelper.SendAsync(model, smtp_SendCompleted, "OK");
            if (!result.Flag)
            {
                throw result.Exception;
            }
        }

        /// <summary>
        /// 邮件发送完毕事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void smtp_SendCompleted(object sender, AsyncCompletedEventArgs e)
        {
            var result = e.UserState as MailAsyncResult;
            if (result != null)
            {
                if (result.message != null)
                {
                    result.message.Dispose();
                }
                if (result.smtp != null)
                {
                    result.smtp.Dispose();
                }
            }
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (e.Cancelled)
            {
                MessageBox.Show("发送被拒绝，请以同步的方式发送，查看拒绝理由!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (result.data.ToString() == "OK")
                MessageBox.Show("发送成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        /// <summary>
        /// 4.5异步发送邮件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btnSendMailAsync_Click(object sender, EventArgs e)
        {
            try
            {
                MailModel model = null;
                if (!checkMail(out model))
                {
                    return;
                }

                MailResult result = await MailHelper.SendMailAsync(model);
                if (!result.Flag)
                {
                    throw result.Exception;
                }

                MessageBox.Show("发送成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }


        }
  
        /// <summary>
        /// 检测页面输入
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        private bool checkMail(out MailModel model)
        {
            model = null;

            int port = 25;
            string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";

            string from = txtSend.Text.Trim();
            string pwd = txtPwd.Text.Trim();
            string smtp = txtSMTP.Text.Trim();
            string strPort = txtPort.Text.Trim();
            bool enableSSL = ckSSL.Checked;

            string to = txtReceive.Text.Trim();
            string cc = txtCopyTo.Text.Trim();
            string bcc = txtBCC.Text.Trim();

            string subject = txtTitle.Text.Trim();
            string content = txtContent.Text.Trim();

            #region 发件邮箱
            if (string.IsNullOrEmpty(from))
            {
                MessageBox.Show("请输入发件邮箱!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            else
            {
                if (!Regex.IsMatch(from, strRegex))
                {
                    MessageBox.Show("请填写正确的发件邮箱!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return false;
                }
            } 
            #endregion

            #region 密码
            if (string.IsNullOrEmpty(pwd))
            {
                MessageBox.Show("请输入登录密码!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            #endregion

            #region SMTP
            if (string.IsNullOrEmpty(smtp))
            {
                MessageBox.Show("请输入SMTP!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            #endregion

            #region 端口
            if (string.IsNullOrEmpty(strPort))
            {
                MessageBox.Show("请输入端口!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            if (!int.TryParse(strPort, out port))
            {
                MessageBox.Show("请输入正确端口!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            #endregion

            #region 收件人
            List<string> to_list = new List<string>();
            if (string.IsNullOrEmpty(to))
            {
                MessageBox.Show("请输入收件人!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            else
            {
                string[] mails = to.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var mail in mails)
                {
                    if (!Regex.IsMatch(mail, strRegex))
                    {
                        MessageBox.Show("请填写正确的收件人!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return false;
                    }
                    to_list.Add(mail);
                }
            } 
            #endregion

            #region 抄送
            List<string> cc_list = new List<string>();
            if (!string.IsNullOrEmpty(cc))
            {
                string[] mails = cc.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var mail in mails)
                {
                    if (!Regex.IsMatch(mail, strRegex))
                    {
                        MessageBox.Show("请填写正确的抄送!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return false;
                    }
                    cc_list.Add(mail);
                }
            }
            #endregion

            #region 密送
            List<string> bcc_list = new List<string>();
            if (!string.IsNullOrEmpty(bcc))
            {
                string[] mails = bcc.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var mail in mails)
                {
                    if (!Regex.IsMatch(mail, strRegex))
                    {
                        MessageBox.Show("请填写正确的密送!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return false;
                    }
                    bcc_list.Add(mail);
                }
            }
            #endregion

            #region 主题
            if (string.IsNullOrEmpty(subject))
            {
                MessageBox.Show("请输入主题!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            #endregion

            #region 正文
            if (string.IsNullOrEmpty(content))
            {
                MessageBox.Show("请输入正文!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            #endregion

            model = new MailModel();
            model.From = from;
            model.Pwd = pwd;
            model.SMTPHost = smtp;
            model.SMTPPort = port;
            model.EnableSsl = enableSSL;

            model.To.AddRange(to_list);
            model.CC.AddRange(cc_list);
            model.Bcc.AddRange(bcc_list);

            model.Subject = subject;
            model.Body = content;

            return true;
        }




    }
}
